package com.qf.service.impl;

import com.qf.dao.AccountDao;
import com.qf.pojo.Account;
import com.qf.service.AccountService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;


/**
 * @Description: 公用常量
 * @Data: 2022/9/1 14:57
 * @Pacakge: com.qf.service.impl
 * @ClassName: AccountServiceImpl
 * @Author: fan
 */
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    private TransactionTemplate transactionTemplate;
    //通过set注入
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public void transfer(String sourceName, String targetName, Double money) {
        //开启事务管理
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                //根据名称查询出转账用户
                Account sourceAccount = accountDao.findAccountByName(sourceName);
                //根据名称查询转入账用户
                Account targetAccount = accountDao.findAccountByName(targetName);
                //转出账户扣钱
                sourceAccount.setMoney(sourceAccount.getMoney() - money);
                //转入账户加钱
                targetAccount.setMoney(targetAccount.getMoney() + money);
                //更新转出账户
                accountDao.updateAccount(sourceAccount);
                //int i = 1/0;
                //更新转入账户
                accountDao.updateAccount(targetAccount);
            }
        });
    }
}
